<?php

namespace App\Services;

use App\Events\Application;
use App\Exceptions\InternalException;
use App\Models\Cert;
use App\Models\CertDown;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class CertService
{
    public function get($search){
        $user_id = Auth::user()->id;
        $sql = Cert::with('application')->with(['application' => function ($query) use ($user_id) {
            $query->user($user_id); // 调用作用域并传递参数
        }])->when($search, function ($query, $search) {
            return $query->where(function($query) use ($search) {
                $query->where('title','like', '%'.$search.'%');
            });
        });
        return $sql;
    }

    public function insert($input,$user_id){
        try {
            if($input['date_type'] == 1){
                $input['end_date'] = null;
            }
            $data = Cert::create($input);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function update($input){
        if($input['date_type'] == 1){
            $input['end_date'] = null;
        }
        $res = [];
        foreach ($input as $k => $v) {
            $res[$k] = $v;
        }
        unset($res['id']);
        try {
            $data = Cert::where('id',$input['id'])->update($res);
            if($data){
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function storeDown($input){
        try {
            $data = CertDown::create($input);
            if($data){
                Application::dispatch('apply','Cert','Cert',$input['user_id'],$data->id,$data->project_id,$data->purpose,'','',0);
                return $data;
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }
    

}